var express = require('express');
let mysqlExec = require('../db/dbMySql.js');
let { Msg, curPath, createJWT ,useJWT} = require('../tools/msg.js');
const { v4: uuidv4 } = require('uuid');
var svgCaptcha = require('svg-captcha');
//引入md5包用来加密密码
var md5 = require('md5');
var router = express.Router();

//生成验证码接口：
router.get('/codeimg', (req, res) => {
    var captcha = svgCaptcha.create({ size: 4, color: true, ignoreChars: '0o1i', noise: 3, background: '#cc9966', width: 100, height: 50 });
    // console.log(captcha);

    res.send(Msg(200, '验证码创建成功', [captcha.data, captcha.text]));
});

//用户登录接口：
router.post('/login', async(req, res) => {

    //接参(用户输入的帐号、密码、验证码、系统生成的验证码)
    let { user = '', pass = '', codes = '', syscode = '' } = req.body;

    if (user == '' || pass == '' || codes == '') {
        res.send(Msg(500, '帐号、密码、验证码都不能为空'));
        return;
    }

    //判断验证码是否正确 
    if (codes.toUpperCase() != syscode.toUpperCase()) {
        res.send(Msg(500, '验证码不正确'));
        return false;
    }


    //查询帐号是否存在：
    let sql = `select password ,username ,mid from e_member where username='${user}'`;
    let [err, datas] = await mysqlExec(sql);
    if (!err) {
        res.send(Msg(500, '用户查询失败'));
        return;
    }

    //先判断帐号是否正确
    if (datas.length == 1) { //帐号正确
        //再判断密码是否正确
        if (md5(pass) == datas[0].password) {

            let jwtData = createJWT(datas[0].mid, user);
            res.send(Msg(200, '登录成功', [jwtData]));
        } else {
            res.send(Msg(500, '密码不正确'));
        }
    } else {
        res.send(Msg(500, '帐号不正确'));
    }


});


//注册新用户接口：
router.post('/register', async(req, res) => {

    //接参(用户输入的帐号、密码、确认密码)
    let { user = '', pwd = '', repwd = '' } = req.body;

    if (user == '' || pwd == '' || repwd == '') {
        res.send(Msg(500, '帐号、密码及确认密码都不能为空'));
        return;
    }

    if (pwd != repwd) {
        res.send(Msg(500, '两次密码不一致'));
        return;
    }

    //查询当前用户是否注册过：
    let sql = `select count(mid) as n from e_member where username='${user}'`;
    let [err, datas] = await mysqlExec(sql);
    if (!err) {
        res.send(Msg(500, '帐号是否存在查询失败'));
        return;
    }

    if (datas[0].n == 1) { //该用户已注册过
        res.send(Msg(500, '该用户已注册过'));
        return;
    }

    //添加用户：
    sql = `insert into e_member(mid,username,password,createdate)values('${uuidv4()}','${user}','${md5(pwd)}','${new Date().getTime()}')`;

    // console.log(md5('123'), md5('123').length);

    // console.log(md5('hello'), md5('hello').length);

    let [e, d] = await mysqlExec(sql);
    if (e && d.affectedRows == 1) {
        res.send(Msg(200, '注册成功'));
    } else {
        res.send(Msg(500, '注册失败'));
    }
});

//根据已登录的用户id查询用户个人信息：
router.get('/userinfo', async(req, res) => {
    //接参(jwt数据)
    let { jwtdata = '' } = req.query;
    //使用JWT数据：
    let jwtObj = useJWT(jwtdata);
    if (!jwtObj) {
        res.send(Msg(500, '非法访问! 用户未登录'));
        return;
    }

    //查询用户个人信息：
    let sql = `select * from e_member where mid='${jwtObj.uid}'`;
    let [err, data] = await mysqlExec(sql);
    if (err) {
        res.send(Msg(200, '个人信息查询成功', data));
    } else {
        res.send(Msg(500, '个人信息查询失败'));
    }

});


//根据已登录的用户id修改用户个人信息：
router.post('/userinfo', async(req, res) => {
    //接参(jwt数据)
    let { jwtdata = '', realname, sex, birthday } = req.body;
    //使用JWT数据：
    let jwtObj = useJWT(jwtdata);
    if (!jwtObj) {
        res.send(Msg(500, '非法访问'));
        return;
    }

    //查询用户个人信息：
    let sql = `update  e_member set realname='${realname}',sex='${sex}',birthdate='${birthday}' where mid='${jwtObj.uid}'`;
    let [err, data] = await mysqlExec(sql);
    if (err && data.affectedRows == 1) {
        res.send(Msg(200, '个人信息修改成功'));
    } else {
        res.send(Msg(500, '个人信息修改失败'));
    }

});

module.exports = router;